package pokemon;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import pokemon.GUI.Mode;

public class GUI extends JFrame
{
	private JPanel content=new JPanel();
	private Pokedex dex;
	private ArrayList<String> pokeNames;
	public static enum Mode { INSERT, COMPLETION };
	private Mode mode = Mode.INSERT;
	private JTextField field;
	private Pokemon currentPoke;
	public GUI(Pokedex dex)
	{
		super();
		this.dex = dex;
		createList();
		String title = "";
    	setTitle(title);
    	setLocation(0,0);
    	content.setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
    	content.setLayout(new BorderLayout());
    	content.setBackground(Color.WHITE);
    	setContentPane(content);
		this.add(makeWestSide(),BorderLayout.WEST);
		makeMenus();
		
	
		
		this.addWindowListener(new java.awt.event.WindowAdapter() {
		    public void windowClosing(WindowEvent winEvt) {
		        System.exit(0); 
		    }
		});
	}
	private void createList()
	{
		pokeNames=new ArrayList<String>();
		for(Pokemon p: dex)
		{
			pokeNames.add(p.getName());
		}
	}
	private JPanel makeWestSide()
	{
		JPanel testBug=new JPanel();
  	
		testBug.add(makeIconWindow());
		testBug.setBackground(Color.BLACK);
		return testBug;
	}
	private JPanel makeIconWindow()
	{
		System.out.println("Icon Window");
		MyPanel testBug=new MyPanel();
		testBug.setLayout(new GridBagLayout());
    	GridBagConstraints c = new GridBagConstraints();
    	
    	
    	
		//testBug.setBorder(BorderFactory.createEmptyBorder(130,20,20,20));
		//Add the white square where the icon will be north.
		field = new JTextField("Enter Pokemon Name");
		c.fill = GridBagConstraints.HORIZONTAL;
		//c.anchor = GridBagConstraints.FIRST_LINE_START; //bottom of space
		c.insets = new Insets(100,15,0,15);  //top padding
		//c.gridx = 1;       //aligned with button 2
		//c.gridwidth = 2;   //2 columns wide
		//c.gridy = 2;       //third row
		testBug.add(field,c);
		field.setEditable(true);
		field.getDocument().addDocumentListener(new DocumentListener() 
		{
			@Override
			public void insertUpdate(DocumentEvent e) 
			{
                currentPoke = dex.getPokemon(field.getText());
                if(currentPoke!=null)
                {
                	System.out.println(currentPoke.getName());
                	System.out.println(currentPoke.getId());
                }
				//System.out.println("Change1");
				if (e.getLength() != 1) 
				{
		            return;
		        }
				//System.out.println("Change2");
		        int pos = e.getOffset();
		        String content = null;
		        try 
		        {
		            content = field.getText(0, pos + 1);
		        } 
		        
		        catch (Exception ex) 
		        {
		            ex.printStackTrace();
		        }
		         
		        // Find where the word starts
		        int w;
		        for (w = pos; w >= 0; w--) {
		            if (! Character.isLetter(content.charAt(w))) {
		                break;
		            }
		        }
		        if (pos - w < 2) {
		            // Too few chars
		            return;
		        }
		       // System.out.println("Change4441"); 
		        
		        String prefix = content.substring(w + 1);
		        int n = Collections.binarySearch(pokeNames, prefix);
		        if (n < 0 && -n <= pokeNames.size()) 
		        {
		            String match = pokeNames.get(-n - 1);
		            if (match.startsWith(prefix)) 
		            {
		                // A completion is found
		                String completion = match.substring(pos - w);
		               
		                //System.out.println("completion found");
		                //field.setText(field.getText()+completion);
		                // We cannot modify Document from within notification,
		                // so we submit a task that does the change later
		                SwingUtilities.invokeLater(
		                        new CompletionTask(completion, pos+1));
		            }
		        } else {
		        	System.out.println("nothing found");
		            // Nothing found
		            mode = Mode.INSERT;
		        }
			}
			@Override
			public void removeUpdate(DocumentEvent e) 
			{
			}
			@Override
			public void changedUpdate(DocumentEvent e) 
			{
			}	
		});
		return testBug;
	}
	public void repaint()
	{
		//super.repaint();
	}
	private JPanel makeButtons()
	{
		JPanel testBug=new JPanel();
		testBug.setLayout(new GridBagLayout());
    	GridBagConstraints c = new GridBagConstraints();
    	BufferedImage startImg = null,pauseImg = null;
    	try 
    	{
    	    startImg = ImageIO.read(new File("start.jpg"));
    	    pauseImg = ImageIO.read(new File("pause.jpg"));
    	}
    	catch(Exception e)
    	{
    		System.out.println(e);
    	}
//		playButton.addActionListener(new ActionListener()
//        {
//            public void actionPerformed(ActionEvent evt) 
//	   		{
//            	try 
//            	{
//					req.activate();
//				} 
//            	catch (Exception e) 
//            	{
//					e.printStackTrace();
//				}
//            	playButton.setEnabled(false);
//            	pauseButton.setEnabled(true);
//	   		}
//        });
    	return testBug;
	}
	private void makeMenus()
    {
    	JMenuBar mbar= new JMenuBar();
    	JMenu menu;
    	mbar.add(menu=makeMenu("File"));
    	menu.add(makeMenuItem("Quit",new ActionListener()
    	{
    		public void actionPerformed(ActionEvent e)
    		{
    			System.exit(0);
    		}
    	}));
    	/*menu.help
    	 */
    	 setJMenuBar(mbar);
    }
	private JMenu makeMenu(String resource)
    {
    	JMenu menu=new JMenu();
    	configureAbstractButton(menu,resource);
    	return menu;
    }
	private void configureAbstractButton(AbstractButton button, String resource)
    {
        String title = resource;
        int i = title.indexOf('&');
        int mnemonic = 0;
        if (i >= 0)
        {
            mnemonic = title.charAt(i + 1);
            title = title.substring(0, i) + title.substring(i + 1);
            button.setText(title);
            button.setMnemonic(Character.toUpperCase(mnemonic));
            button.setDisplayedMnemonicIndex(i);
            
        }
        else
            button.setText(title);
    }
	private JMenuItem makeMenuItem(String resource, ActionListener listener)
    {
    	JMenuItem item=new JMenuItem();
    	configureMenuItem(item,resource,listener);
    	return item;	
    }
    private void configureMenuItem(JMenuItem item, String resource, ActionListener listener)
    {
    	
        configureAbstractButton(item, resource);
        item.addActionListener(listener);
        
        try
        {
            //String accel = resources.getString(resource + ".accel");
            
            String accel = (resource + ".accel");
            String metaPrefix = "@";
            if (accel.startsWith(metaPrefix))
            {
                int menuMask = getToolkit().getMenuShortcutKeyMask();
                KeyStroke key = KeyStroke.getKeyStroke(KeyStroke.getKeyStroke(
                        accel.substring(metaPrefix.length())).getKeyCode(),
                        menuMask);
                item.setAccelerator(key);
            }
            else
            {
                item.setAccelerator(KeyStroke.getKeyStroke(accel));
            }
            
        }
        catch (Exception e)
        {
            // no accelerator
        }
    }
    private class CompletionTask implements Runnable 
    {
        String completion;
        int position;
        CompletionTask(String completion, int position) 
        {
            this.completion = completion;
            this.position = position;
        }
         
        public void run() {
        	
        	String text= field.getText();
        	
        	String textTwo = (String) text.subSequence(0, position);
        	
        	//System.out.println(textTwo);
        	//System.out.println(completion);
        	
            //textTwo.concat(completion);
            //textTwo.concat((String) text.subSequence(position, text.length()));
        	String test3 = text.concat(completion);
        	
            field.setText(test3);
            
            //System.out.println(field.getText());
            
            field.setCaretPosition(position + completion.length());
            field.moveCaretPosition(position);
            mode = Mode.COMPLETION;
        }
    }
    public class MyPanel extends JPanel 
    {
    	public MyPanel()
    	{
    		super();
    	}
    	public MyPanel(BorderLayout borderLayout) 
    	{
    		super(borderLayout);
			// TODO Auto-generated constructor stub
		}

		@Override
    	public void paintComponent(Graphics g) 
    	{
    		super.paintComponent(g);
    	    Graphics2D g2 = (Graphics2D) g;
    	    try
    	    {
    	    	g2.drawImage(currentPoke.myImage, 0, 0, null);
    	    }
    	    catch(Exception e)
    	    {
    	    	System.out.println(e);
    	    }
    	    repaint();
//    	    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    	}
    }
 
    private class CommitAction extends AbstractAction 
    {
        public void actionPerformed(ActionEvent ev) 
        {
            if (mode == Mode.COMPLETION) {
                int pos = field.getSelectionEnd();
                String textTwo = (String) field.getText().subSequence(0, pos);
                textTwo.concat(" ");
                textTwo.concat((String) field.getText().subSequence(pos, field.getText().length()));
                field.setCaretPosition(pos + 1);
                mode = Mode.INSERT;
            } else {
            	field.replaceSelection("\n");
            }
        }
    }
}
